package ru.lenwp.operation.admin;

import ru.lenwp.context.Context;
import ru.lenwp.model.OperationInfo;
import ru.lenwp.model.User;
import ru.lenwp.operation.Operation;

import java.util.Iterator;

import static ru.lenwp.util.ConsoleUtil.askString;

/**
 * Created by Lenar on 04.08.2014.
 */
public class EditPasswordOperation implements Operation {

    private final Context context;

    public EditPasswordOperation(Context context) {
        this.context = context;
    }

    public void editPassword() {
        System.out.println("Сменить пароль");
        System.out.println("Введите логин");
        String login = askString();
        User currentUser = null;
        Iterator<User> userIterator = context.getUserDao().allUser().iterator();
        while (userIterator.hasNext() && currentUser == null) {
            User user = userIterator.next();
            if (user.getLogin().equals(login)) {
                currentUser = user;
            }
        }
        if (currentUser == null) {
            throw new RuntimeException("Пользователь с логином " + login + " не найден.");
        }
        System.out.println("Введите старый пароль пароль");
        String oldPassword = askString();
        if (oldPassword.equals(currentUser.getPassword())) {
            System.out.println("Введите новый пароль пароль");
            String newPassword = askString();
            currentUser.setPassword(newPassword);
            return;
        }
        throw new RuntimeException("Пароли не совпадают.");
    }

    @Override
    public OperationInfo execute() {
        editPassword();
        return null;
    }

    @Override
    public String getOperationName() {
        return "Смена пароля";
    }
}

